package com.voja.mrvica2.db;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Locale;

import android.content.Context;

import com.voja.mrvica2.App;
import com.voja.mrvica2.Entry;

public class EntryGroup extends DB {

    public EntryGroup(Context context) {
        super(context);
    }
    
    public long getLastUpdateTimeStamp() {
        long result = 0;
        cursor = query("SELECT stamp FROM sync WHERE key='continents';");
        if (cursor != null) {
            while (cursor.moveToNext()) {
                result = cursor.getLong(0);
            }
        }
        return result;
    }
    
    public boolean expired() {
        long    lastStamp = getLastUpdateTimeStamp();
        long    now       = Calendar.getInstance().getTimeInMillis();
        
        return (lastStamp + App.CACHE_LIFETIME) < now;
    }
    
    public ArrayList<Entry> get() {
        ArrayList<Entry> result = new ArrayList<Entry>();
        
        cursor = query("SELECT * FROM continents ORDER BY name");
        if (cursor != null) {
            Entry e;
            while (cursor.moveToNext()) {
                e = new Entry();
                e.set(
                    cursor.getInt(cursor.getColumnIndex("id")),
                    cursor.getString(cursor.getColumnIndex("name")),
                    cursor.getString(cursor.getColumnIndex("image")),
                    "",
                    ""
                );
                result.add(e);
            }
        }
        
        return result;
    }
    
    public boolean save(ArrayList<Entry> data) {
        boolean ret = true;
        
        // insert continents
        Entry e;
        String sql;
        for (int i=0; i<data.size(); i++) {
            e = data.get(i);
            
            // insert if there's no Entry Group
            sql = String.format(Locale.US,
            					"INSERT OR IGNORE INTO continents(id, name) VALUES(%d, '')", 
                                e.getId());
            execute(sql);
            
            // update EntryGroup data
            sql = String.format(Locale.US,
            					"UPDATE continents SET name='%s', image='%s' WHERE id=%d", 
                                e.getTitle(), e.getImage(), e.getId());
            ret = ret && (execute(sql)>0);
        }
        
        // update sync TimeStamp
        if (ret) {
            sql = String.format("UPDATE sync SET stamp=%s WHERE key='continents';",
                                Calendar.getInstance().getTimeInMillis());
            ret = ret && (execute(sql)>0);
        }
        
        return ret;
    }
}
